import React, { useState, useRef, useEffect, useMemo } from 'react';
import { Button, Card, App } from 'antd';
import { SoundOutlined, AudioMutedOutlined, MutedOutlined } from '@ant-design/icons';
import metahumanService from '@/api/services/metahumanService';
import './styles.css';
import { useMetahumanStore } from '@/store/metahumanStore';
import { SvgIcon } from '../icon';
import useWindowWidth from '@/hooks/event/use-window-width';
import { useParams } from '@/router/hooks';

interface DigitalHumanProps {
  className?: string;
  style?: React.CSSProperties;
  makeBackgroundTransparent?: boolean;
}

const DigitalHuman: React.FC<DigitalHumanProps> = ({
  className,
  style,
  makeBackgroundTransparent = true
}) => {
  const { message } = App.useApp();
  const { isPc } = useWindowWidth();

  const {appId: appIdFromParams} = useParams() as {appId: string}


  const {
    virtualAvatarEnabled,
    virtualAvatarName,
    virtualAvatarUrl,
    setMetahumanUrl,
    virtualAvatarId: avatarId,
    // WebRTC状态
    isConnected,
    setIsConnected,
    isLoading,
    isMuted,
    pc,
    videoStream,
    audioStream,
    // WebRTC方法
    startWebRTCConnection,
    stop: stopMetahuman,
    setIsMuted,
    setIsLoading,
    setTaskId,
    taskId,
    // 添加定时器相关方法
    setPollInterval,
    clearPollInterval,
    setAbortController,
    setIsMetahumanStart,
    isMetahumanStart,
    permissionConfig,
    appId,
    setIsMuteToggle,
    isMuteToggle
  } = useMetahumanStore();

  // 本地ref
  // const videoRef = useRef<HTMLVideoElement>(null);
  const audioRef = useRef<HTMLAudioElement>(null);
  const displayVideoRef = useRef<HTMLVideoElement>(null);

  const isStart = useRef(false);

  // 5分钟无操作自动停止相关
  const inactivityTimerRef = useRef<NodeJS.Timeout | null>(null);
  const INACTIVITY_TIMEOUT = 5 * 60 * 1000; // 5分钟

  // 视频时间监控相关
  const videoTimeMonitorRef = useRef<NodeJS.Timeout | null>(null);
  const VIDEO_TIME_MONITOR_INTERVAL = 1000; // 每秒检查一次
  const VIDEO_TIME_STUCK_THRESHOLD = 5000; // 5秒未更新阈值

  // 页面加载后自动设置静音状态为true，解决自动播放问题
  // useEffect(() => {
  //   // 在组件挂载后立即设置静音状态为true
  //   setIsMuted(false);
  // }, []);

  // 确保所有媒体元素都正确应用静音状态
  useEffect(() => {
    // 只在组件初始化时设置一次，避免后续重新渲染
    // if (audioRef.current && !audioRef.current.srcObject) {
    //   audioRef.current.muted = isMuted;
    //   audioRef.current.volume = isMuted ? 0 : 1.0;
    // }
    // if (videoRef.current && !videoRef.current.srcObject) {
    //   videoRef.current.muted = isMuted;
    //   videoRef.current.volume = isMuted ? 0 : 1.0;
    // }
    if (displayVideoRef.current && !displayVideoRef.current.srcObject) {
      displayVideoRef.current.muted = isMuted;
      displayVideoRef.current.volume = isMuted ? 0 : 1.0;
    }
  }, []); // 只在组件挂载时执行一次

  // 重置无操作定时器
  const resetInactivityTimer = () => {
    if (inactivityTimerRef.current) {
      clearTimeout(inactivityTimerRef.current);
    }

    if (virtualAvatarEnabled && isConnected) {
      inactivityTimerRef.current = setTimeout(() => {
        console.log('5分钟无操作，自动停止数字人');
        stopMetahuman();
        message.info('由于长时间无操作，数字人已自动停止');
      }, INACTIVITY_TIMEOUT);
    }
  };

  // 启动视频时间监控
  const startVideoTimeMonitor = () => {
    if (videoTimeMonitorRef.current) {
      clearInterval(videoTimeMonitorRef.current);
    }

    if (virtualAvatarEnabled && isConnected && displayVideoRef.current) {
      console.log('启动视频时间监控');
      const video = displayVideoRef.current;
      let lastUpdateTime = Date.now();
      let lastVideoTime = video.currentTime;
      
      videoTimeMonitorRef.current = setInterval(() => {
        if (video && video.srcObject && !video.paused) {
          const currentTime = video.currentTime;
          const now = Date.now();
          
          // 如果视频时间没有变化，检查是否超过阈值
          if (Math.abs(currentTime - lastVideoTime) < 0.1) { // 允许0.1秒的误差
            const timeSinceLastUpdate = now - lastUpdateTime;
            if (timeSinceLastUpdate >= VIDEO_TIME_STUCK_THRESHOLD) {
              console.log('视频时间超出5秒未更新，自动停止数字人', {
                currentTime,
                lastVideoTime,
                timeSinceLastUpdate,
                threshold: VIDEO_TIME_STUCK_THRESHOLD
              });
              stopMetahuman();
              message.warning('视频流异常，数字人已自动停止');
              return;
            }
          } else {
            // 视频时间有更新，重置计时器
            lastUpdateTime = now;
            lastVideoTime = currentTime;
          }
        }
      }, VIDEO_TIME_MONITOR_INTERVAL);
    }
  };

  // 停止视频时间监控
  const stopVideoTimeMonitor = () => {
    if (videoTimeMonitorRef.current) {
      clearInterval(videoTimeMonitorRef.current);
      videoTimeMonitorRef.current = null;
      console.log('停止视频时间监控');
    }
  };

  // 用户活动监听器
  const handleUserActivity = () => {
    resetInactivityTimer();
  };

  // 设置用户活动监听
  useEffect(() => {
    if (virtualAvatarEnabled && isConnected) {
      const events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart', 'click'];

      events.forEach(event => {
        document.addEventListener(event, handleUserActivity, true);
      });

      // 初始启动定时器
      resetInactivityTimer();

      return () => {
        events.forEach(event => {
          document.removeEventListener(event, handleUserActivity, true);
        });

        if (inactivityTimerRef.current) {
          clearTimeout(inactivityTimerRef.current);
        }
      };
    }
  }, [virtualAvatarEnabled, isConnected]);

  // 清理定时器
  useEffect(() => {
    return () => {
      if (inactivityTimerRef.current) {
        clearTimeout(inactivityTimerRef.current);
      }
      // 清理视频时间监控
      stopVideoTimeMonitor();
    };
  }, []);

  useEffect(() => {
    if (virtualAvatarEnabled) {
      !taskId && start();
    } else {
      stopMetahuman();
    }
  }, [virtualAvatarEnabled]);

  useEffect(() => {
    if (virtualAvatarEnabled && isStart.current) {
      start();
    }
    isStart.current = true;
  }, [virtualAvatarName, appId]);

  // 轮询检查数字人状态
  const checkMetahumanStatus = async (taskId: string) => {
    if (!taskId) return;

    try {
      const response = await metahumanService.checkMetahuman(taskId);

      if (response?.status === 'restart') {
        clearPollInterval();
        stopMetahuman();
        return false;
      }

      if (response?.status === 'active' && response.metahumanUrl && response?.coturnUrl) {
        setMetahumanUrl(response.metahumanUrl);

        // 清理定时器
        clearPollInterval();

        const { origin } = new URL(response.metahumanUrl);
        const hostname = new URL(origin).hostname;
        const port = new URL(origin).port;
        let api = "/offer";
        if (port) {
          api = `/api/openapi/proxy/${hostname}:${port}/offer`;
        } else {
          api = `/api/openapi/proxy/${hostname}/offer`;
        }

        // 使用store中的WebRTC连接方法
        await startWebRTCConnection(api, response.coturnUrl, makeBackgroundTransparent);
        return true;
      }

      return false;
    } catch (error) {
      console.error('检查数字人状态失败:', error);
      message.error(error?.message || '数字人启动失败');
      // 检查失败时设置loading为false
      setIsLoading(false);
      return false;
    }
  };

  const start = async () => {
    if (isLoading) {
      // message.info('数字人正在连接中，请稍后再试');
      setIsMetahumanStart(false);
      return;
    }
    await stopMetahuman();

    if (!avatarId) {
      // message.error('请提供数字人ID和应用ID');
      setIsMetahumanStart(false);
      return;
    }

    try {
      // 启动数字人时设置loading状态为true
      console.log('开始启动数字人，设置isLoading为true');
      setIsLoading(true);

      const abortController = new AbortController();
      // 创建 AbortController 用于取消请求
      setAbortController(abortController);
      setIsMetahumanStart(true);
      const activeAppId = appId || appIdFromParams;
      const startResponse = await metahumanService.startMetahuman(avatarId, activeAppId, abortController.signal);
      // if (!isMetahumanStart && startResponse?.taskId) {
      //   metahumanService.stopMetahuman(startResponse?.taskId);
      //   return;
      // }

      if (startResponse?.taskId) {
        console.log('数字人启动成功，taskId:', startResponse.taskId);
        await setTaskId(startResponse.taskId);


        // 使用store管理定时器
        const interval = setInterval(async () => {
          await checkMetahumanStatus(startResponse.taskId);
        }, 3000);

        setPollInterval(interval);

        // 设置超时，如果120秒内没有连接成功，则设置loading为false
        // setTimeout(() => {
        //   if (!isConnected) {
        //     console.log('数字人启动超时，设置isLoading为false');
        //     setIsLoading(false);
        //     stopMetahuman();
        //   }
        // }, 120000);

      } else {
        console.log('数字人启动失败，没有返回taskId');
        setIsLoading(false);
        stopMetahuman();
        startResponse?.message && message.error(startResponse.message);
      }
    } catch (error) {
      console.error('启动数字人异常:', error);
      stopMetahuman();
      message.error('启动数字人失败，请重试');
    } finally {
      setIsMetahumanStart(false);
    }
  };

  // 调试：监听store状态变化
  useEffect(() => {
    console.log('Store状态变化:', {
      isConnected,
      isLoading,
      isMuted,
      hasVideoStream: !!videoStream,
      // hasAudioStream: !!audioStream,
      pcState: pc?.connectionState,
      iceState: pc?.iceConnectionState
    });
  }, [isConnected, isLoading, isMuted, videoStream, pc]);

  // 同步视频流到显示元素
  useEffect(() => {
    console.log('视频流同步useEffect触发:', {
      videoStream: !!videoStream,
      displayVideoRef: !!displayVideoRef.current,
      isConnected
    });

    if (videoStream && displayVideoRef.current) {
      console.log('设置视频流到显示元素:', videoStream);
      const video = displayVideoRef.current;

      // 强制设置静音状态，确保可以自动播放
      video.muted = true;
      video.volume = 0;

      // 设置流之前先确保静音
      video.srcObject = videoStream;

      // 添加视频加载事件监听
      // 先绑定事件监听器，再设置srcObject
      const handleLoadedData = () => {
        console.log('视频数据加载完成');
        // 强制确保静音状态正确
        video.muted = true;
        video.volume = 0;
      };
      const handleCanPlay = () => {
        console.log('视频可以播放');
        // 强制确保静音状态正确
        video.muted = true;
        video.volume = 0;

        // 使用延迟播放策略，给浏览器更多时间处理
        setTimeout(() => {
          if (video.paused) {
            console.log('延迟尝试播放视频');
            // 再次确保静音状态
            video.muted = true;
            video.volume = 0;

            video.play().catch(e => {
              console.log('自动播放失败:', e);
              // 如果仍然失败，尝试更激进的策略
              if (e.name === 'NotAllowedError') {
                console.log('尝试使用静音播放策略');
                // 确保完全静音
                video.muted = true;
                video.volume = 0;
                // 再次尝试播放
                setTimeout(() => {
                  video.play().catch(e2 => {
                    console.log('静音播放仍然失败:', e2);
                  });
                }, 100);
              }
            });
          }
        }, 200);
      };
      const handleError = (e: Event) => {
        console.error('视频加载错误:', e);
      };
      const handlePause = () => {
        console.log('视频暂停');
      };
      const handlePlay = () => {
        console.log('视频开始播放');
      };
      const handleLoadedMetadata = () => {
        console.log('视频元数据加载完成');
      };
      const handleTimeUpdate = () => {
        // console.log('视频时间更新', video.currentTime);
        // if (!isConnected) {
        //   setIsConnected(true);
        // }
      };
      const handleWaiting = () => {
        console.log('视频等待数据');
      };
      const handleStalled = () => {
        console.log('视频数据不足');
      };

      video.addEventListener('loadeddata', handleLoadedData);
      video.addEventListener('canplay', handleCanPlay);
      video.addEventListener('error', handleError);
      video.addEventListener('timeupdate', handleTimeUpdate);
      video.addEventListener('play', handlePlay);
      video.addEventListener('pause', handlePause);
      video.addEventListener('loadedmetadata', handleLoadedMetadata);
      video.addEventListener('waiting', handleWaiting);
      video.addEventListener('stalled', handleStalled);

      return () => {
        video.removeEventListener('loadeddata', handleLoadedData);
        video.removeEventListener('canplay', handleCanPlay);
        video.removeEventListener('error', handleError);
        video.removeEventListener('timeupdate', handleTimeUpdate);
        video.removeEventListener('play', handlePlay);
        video.removeEventListener('pause', handlePause);
        video.removeEventListener('loadedmetadata', handleLoadedMetadata);
        video.removeEventListener('waiting', handleWaiting);
        video.removeEventListener('stalled', handleStalled);
      };
    }
  }, [videoStream, isConnected, displayVideoRef]);

  // 新增：监听视频元素引用变化，确保事件监听器正确绑定
  useEffect(() => {
    if (displayVideoRef.current && videoStream) {
      const video = displayVideoRef.current;

      // 如果视频流已经设置但还没有事件监听器，重新绑定
      if (video.srcObject === videoStream) {
        console.log('重新绑定视频事件监听器');
        // 强制确保静音状态正确，但不重新设置流
        if (!video.muted) {
          video.muted = true;
          video.volume = 0;
        }
        // 这里可以添加额外的事件监听逻辑
      }
    }
  }, [displayVideoRef.current, videoStream]);

  // 新增：视频流设置后的状态检查和自动播放
  useEffect(() => {
    if (displayVideoRef.current && videoStream && isConnected) {
      const video = displayVideoRef.current;

      // 强制设置静音状态
      video.muted = true;
      video.volume = 0;

      // 延迟检查视频状态，确保流数据已经加载
      const checkVideoStatus = setTimeout(() => {
        console.log('检查视频状态:', {
          readyState: video.readyState,
          paused: video.paused,
          currentTime: video.currentTime,
          duration: video.duration,
          srcObject: !!video.srcObject
        });

        // 再次确保静音状态
        video.muted = true;
        video.volume = 0;

        // 如果视频暂停且可以播放，尝试自动播放
        if (video.paused && video.readyState >= 2) {
          console.log('尝试自动播放视频');

          // 使用延迟播放策略
          setTimeout(() => {
            // 再次确保静音状态
            video.muted = true;
            video.volume = 0;

            video.play().catch(e => {
              console.log('自动播放失败:', e);
              // 如果失败，尝试更激进的策略
              if (e.name === 'NotAllowedError') {
                console.log('尝试使用静音播放策略');
                // 确保完全静音
                video.muted = true;
                video.volume = 0;
                // 再次尝试播放
                setTimeout(() => {
                  video.play().catch(e2 => {
                    console.log('静音播放仍然失败:', e2);
                  });
                }, 100);
              }
            });
          }, 300);
        }
      }, 1000);

      return () => clearTimeout(checkVideoStatus);
    }
  }, [videoStream, isConnected]);

  // 同步音频流到音频元素
  // useEffect(() => {
  //   if (audioStream && audioRef.current) {
  //     const audio = audioRef.current;
  //     // 强制设置静音状态，确保可以自动播放
  //     audio.muted = true;
  //     audio.volume = 0;
  //     audio.srcObject = audioStream;
  //   }
  // }, [audioStream]);



  const toggleMute = () => {
    setIsMuteToggle(true);
    const newMutedState = !isMuted;
    console.log('切换静音状态:', { from: isMuted, to: newMutedState });

    // 直接操作媒体元素，避免状态变化触发重新渲染
    // if (audioRef.current) {
    //   audioRef.current.muted = newMutedState;
    //   audioRef.current.volume = newMutedState ? 0 : 1.0;
    // }
    // if (videoRef.current) {
    //   videoRef.current.muted = newMutedState;
    //   videoRef.current.volume = newMutedState ? 0 : 1.0;
    // }
    if (displayVideoRef.current) {
      displayVideoRef.current.muted = newMutedState;
      displayVideoRef.current.volume = newMutedState ? 0 : 1.0;
    }

    // 直接操作音频轨道，避免重新设置流
    if (videoStream) {
      const audioTracks = videoStream.getAudioTracks();
      audioTracks.forEach(track => {
        track.enabled = !newMutedState;
      });
    }
    // if (audioStream) {
    //   const audioTracks = audioStream.getAudioTracks();
    //   audioTracks.forEach(track => {
    //     track.enabled = !newMutedState;
    //   });
    // }

    // 最后更新状态，避免触发不必要的重新渲染
    setIsMuted(newMutedState);
  };

  // 监听静音状态变化，同步所有媒体元素的静音状态
  useEffect(() => {
    console.log('静音状态变化，同步媒体元素:', isMuted);

    // 只在isMuted变化时同步媒体元素状态，但避免重新设置流
    // if (audioRef.current) {
    //   audioRef.current.muted = isMuted;
    //   audioRef.current.volume = isMuted ? 0 : 1.0;
    // }
    // if (videoRef.current) {
    //   videoRef.current.muted = isMuted;
    //   videoRef.current.volume = isMuted ? 0 : 1.0;
    // }
    if (displayVideoRef.current) {
      displayVideoRef.current.muted = isMuted;
      displayVideoRef.current.volume = isMuted ? 0 : 1.0;
    }

    // 避免频繁操作音频轨道，只在必要时启用/禁用
    if (videoStream) {
      const audioTracks = videoStream.getAudioTracks();
      audioTracks.forEach(track => {
        // 只有在状态真正改变时才设置
        if (track.enabled === isMuted) {
          console.log('设置视频流音频轨道启用状态:', !isMuted);
          track.enabled = !isMuted;
        }
      });
    }
    // if (audioStream) {
    //   const audioTracks = audioStream.getAudioTracks();
    //   audioTracks.forEach(track => {
    //     // 只有在状态真正改变时才设置
    //     if (track.enabled === isMuted) {
    //       console.log('设置音频流轨道启用状态:', !isMuted);
    //       track.enabled = !isMuted;
    //     }
    //   });
    // }
  }, [isMuted, videoStream, isMuteToggle, displayVideoRef.current]);

  // // 监听音频流变化，确保静音状态正确应用
  // useEffect(() => {
  //   // const audio = audioRef.current;
  //   const audio = displayVideoRef.current;
  //   if (!audio) return;

  //   const handleLoadedMetadata = () => {
  //     // 只在音频流首次加载时设置静音状态，避免后续重新设置
  //     if (!audio.muted && isMuted) {
  //       audio.muted = isMuted;
  //       audio.volume = isMuted ? 0 : 1.0;
  //     }
  //   };

  //   const handleCanPlay = () => {
  //     // 只在音频流首次可以播放时设置静音状态，避免后续重新设置
  //     if (!audio.muted && isMuted) {
  //       audio.muted = isMuted;
  //       audio.volume = isMuted ? 0 : 1.0;
  //     }
  //   };

  //   audio.addEventListener('loadedmetadata', handleLoadedMetadata);
  //   audio.addEventListener('canplay', handleCanPlay);

  //   return () => {
  //     audio.removeEventListener('loadedmetadata', handleLoadedMetadata);
  //     audio.removeEventListener('canplay', handleCanPlay);
  //   };
  // }, [isMuted, videoStream, isMuteToggle, displayVideoRef.current]); // 只在静音状态变化时重新绑定

  // useEffect(() => {
  //   const handleBeforeUnload = () => {
  //     if (pc) {
  //       pc.close();
  //     }
  //   };

  //   window.addEventListener('beforeunload', handleBeforeUnload);
  //   return () => {
  //     window.removeEventListener('beforeunload', handleBeforeUnload);
  //     if (pc) {
  //       pc.close();
  //     }
  //   };
  // }, [pc]);

  // 组件卸载时清理定时器
  useEffect(() => {
    return () => {
      clearPollInterval();
    };
  }, []);

  // 监听视频流变化，自动启动或停止视频时间监控
  useEffect(() => {
    if (videoStream && isConnected) {
      // 延迟启动监控，确保视频元素已经设置好
      const timer = setTimeout(() => {
        startVideoTimeMonitor();
      }, 1000);
      
      return () => {
        clearTimeout(timer);
        stopVideoTimeMonitor();
      };
    } else {
      stopVideoTimeMonitor();
    }
  }, [videoStream, isConnected]);

  useEffect(() => {
    if (!isConnected) {
      setIsMuted(true);
    } else {
      setIsMuted(false);
    }
  }, [isConnected]);

  return (
    <Card
      className={`digital-human ${className || ''}`}
      style={{ ...style, border: 'none', boxShadow: 'none', padding: '0', margin: '0', backgroundColor: 'transparent' }}
    >
      <div className="digital-human-container bg-[transparent]">
        <div className="media-container">
          {/* <audio
            id="metahuman-audio"
            ref={audioRef}
            autoPlay
            muted={true}
            controls={false}
            preload="auto"
          /> */}
          {/* <video
            ref={videoRef}
            autoPlay
            muted={true}
            playsInline
            style={{ display: 'none' }}
          /> */}

          <div
            className={`video-container ${isConnected ? 'connected' : 'disconnected'}`}
            style={{
              position: 'relative',
              display: 'inline-block',
              backgroundColor: 'transparent',
              height: isConnected ? '100%' : '0px',
            }}
          >
            <video
              id="metahuman-video"
              ref={displayVideoRef}
              autoPlay
              playsInline
              muted={true}
              controls={false}
              style={{
                width: '100%',
                maxWidth: '600px',
                height: '100%',
                borderRadius: '8px',
                backgroundColor: 'transparent',
                background: 'transparent',
                objectFit: 'contain',
                border: 'none',
                boxShadow: 'none',
                padding: '0',
                margin: '0',
                /* 减少闪烁的样式 */
                imageRendering: 'crisp-edges',
                backfaceVisibility: 'hidden',
                transform: 'translateZ(0)',
                willChange: 'transform'
              }}
            />
            {/* 调试信息 */}
            {/* <div style={{
                position: 'absolute',
                top: '8px',
                left: '8px',
                background: 'rgba(0, 0, 0, 0.7)',
                color: 'white',
                padding: '4px 8px',
                borderRadius: '4px',
                fontSize: '12px',
                zIndex: 10
              }}>
                {isConnected ? '已连接' : '未连接'} | 
                {videoStream ? '有视频流' : '无视频流'} | 
                {audioStream ? '有音频流' : '无音频流'} |
                {displayVideoRef.current?.paused ? '暂停' : '播放中'} |
                {displayVideoRef.current?.readyState || 0}
              </div> */}
            <Button
              type="text"
              // icon={isMuted ? <MutedOutlined /> : <SoundOutlined />}
              icon={isMuted ? <SvgIcon icon="ai-metahuman-mute" size={36}/> : <SvgIcon icon="ai-metahuman-play" size={36}/>}
              onClick={toggleMute}
              style={{
                position: 'absolute',
                right: '8px',
                zIndex: 10,
                background: 'transparent',
                border: '1px solid 0013330F',
                borderRadius: '6px',
                width: '36px',
                height: '36px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                minWidth: '36px',
                padding: '0'
              }}
              title={isMuted ? '取消静音' : '静音'}
              className={`${isPc ? 'top-1' : 'top-16'}`}
            />
          </div>

          {
            !isConnected && (
              <div className="relative w-full h-full">
                <img
                  src={virtualAvatarUrl}
                  alt={virtualAvatarName}
                  className="w-full h-full rounded object-cover"
                  style={{ opacity: 0.5, width: '300px' }}
                />
                {virtualAvatarUrl && <div
                  className={
                    isPc
                      ? "absolute right-4 bottom-4 rounded px-4 py-2 flex items-center"
                      : "absolute top-1/2 right-0 transform -translate-y-1/2 rounded px-4 py-2 flex items-center"
                  }
                  style={{
                    background: '#FFFFFFD9',
                    border: '1px solid #0013330F',
                    boxShadow: '0 2px 8px rgba(0,0,0,0.03)',
                    color: '#4E5969',
                    zIndex: 10,
                    fontFamily: 'PingFang SC',
                    fontWeight: 400,
                    fontSize: '14px',
                  }}
                >
                  {isLoading ? `正在呼叫${virtualAvatarName}` : `${virtualAvatarName}在忙，请稍后再试`}
                  <span
                    className="ml-2 text-blue-500 cursor-pointer hover:underline w-[70px]"
                    onClick={isLoading ? () => { } : start}
                  >
                    <SvgIcon icon="ai-chat-refresh" size={15} />
                    {isLoading ? '连线中' : '重连'}
                  </span>
                </div>
                }
              </div>
            )
          }
        </div>
      </div>
    </Card>
  );
};

export default DigitalHuman; 